
//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by 孙明海 on 16/2/18.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit

extension UITextView {
    var emoticonText: String {
        //        print(attributedText)
        let attrText = attributedText
        var str = String()
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            if let emoticonAttachment = dict["NSAttachment"] as? EmoticonAttachment {
                str += emoticonAttachment.emoticon.chs!
            } else {
                str += attrText.string
            }
        }
        return str
    }
    
    /// 插入表情符号
    func insertEmoticon(emoticon: Emoticon) {
        //        print(emoticon)
        // 空白表情
        if emoticon.isEmpty {
            return
        }
        // 删除表情
        if emoticon.isRemoved {
            deleteBackward()
            return
        }
        // emoji 表情
        if let emoji = emoticon.emoji {
            insertText(emoji)
            return
        }
        // 图片表情
        insertImageEmoticon(emoticon)
    }
    /// 插入表情图片
    private func insertImageEmoticon(emoticon: Emoticon) {
        let attach = EmoticonAttachment(emoticon: emoticon)
        
        let attr = attach.imageText(font!)
        
        let attrText = attributedText
        let mAttr = NSMutableAttributedString(attributedString: attrText)
        
        let range = selectedRange
        mAttr.replaceCharactersInRange(range, withAttributedString: attr)
        attributedText = mAttr
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }

}
